import { ref } from 'vue'
import { addZone, findAllZone, findZone, delZone, updateZone } from '../apis/zoneAPI'

export default () => {
  const res = ref<ResponseModel<ZoneModel>>()
  const zones = ref<ZoneModel[]>([])
  const zone = ref<ZoneViewModel>()

  async function all(args = {}) {
    const { data } = await findAllZone(args)
    zones.value = data
  }

  async function del(id: number) {
    await delZone(id)
  }

  async function update(id: number, zone: Partial<ZoneModel>) {
    await updateZone(id, zone)
  }

  async function add(zone: ZoneModel) {
    await addZone(zone)
  }

  async function find(id: number) {
    const { data } = await findZone(id)
    zone.value = data
  }

  async function calculateZoneConfig(id: number, margin = 40, offsetWidth: number, offsetHeight: number) {
    const { data } = await findZone(id)
    const { minX, minY, maxX, maxY } = data.CalculateZone

    const startY = 2 * 10 * (Math.floor(minY / 2 / 10) - 1)
    let endY = 2 * 10 * (Math.floor(maxY / 2 / 10) + 4)
    const caclHeight = endY - startY

    const startX = 2 * 10 * Math.floor(minX / 2 / 10)
    let endX = 2 * 10 * (Math.ceil(maxX / 2 / 10) + 4)
    const caclWidth = endX - startX

    const width = Math.max(caclWidth + margin * 2, offsetWidth)
    const height = Math.max(caclHeight + margin * 2, offsetHeight)
    endX = 2 * 10 * Math.floor((width - margin * 2) / 2 / 10) + startX
    endY = 2 * 10 * Math.floor((height - margin * 2) / 2 / 10) + startY

    return {
      width,
      height,
      startX,
      endX,
      startY,
      endY,
    }
  }

  return { add, all, del, find, update, calculateZoneConfig, zone, zones, res }
}
